#!/bin/bash

# This connection can happen before or after security-secretstore-setup
# (a oneshot service that configures Vault) has already run. The first
# case happens when the content interface is auto-connected and the
# external snap is installed before the edgexfoundry
# snap.
#
# The latter happens when the order is swapped *and* the connection
# is manually connected. In this case since security-secretstore-setup
# (which runs file-token-provider) has already run, the token for
# the external snap will have already been generated, and thus will be
# hidden when the content interface directory from the
# external snap is bind mounted on top of the existing
# /secrets directory.
#
# The corresponding prepare hook (which runs before the bind mount) for
# this content interface is used to copy the token to /tmp.
#
# This script checks for the token in /tmp, and if found, moves it to
# the new bind mounted directory.
#
# This script also supports the case where the other snap has multiple
# tokens, i.e. app-service-configurable
# 
# NOTE - one final comment, app-service-configurable is included in the
# edgexfoundry snap to provide for Kuiper integration. It's disabled by
# default, and is hard-coded to use the 'rules-engine' profile. Due to
# the way vault tokens work, both the internal app-service-configurable
# instance, and the instance in the app-service-configurable snap are
# able to share the same token.

SLOTDIRS=$(snapctl get :edgex-secretstore-token --slot source.write)
logger "edgex-secretstore-token: prepare SLOTDIRS=$SLOTDIRS"
DIRS=$(jq -r '.[]'  <<< "$SLOTDIRS" ) 

for tokenpath in $DIRS;
do
    filename=$(basename $tokenpath)
    logger "edgex-secretstore-token: connect $filename"
    APP_SVC_TOKEN="/tmp/${filename}-secrets-token.json"
    TARGET_PATH="$SNAP_DATA/secrets/${filename}/secrets-token.json"

    if [ -f "$APP_SVC_TOKEN" ]; then
        logger "edgex-secretstore-token: token found in $APP_SVC_TOKEN; moving to $TARGET_PATH"
        mv "$APP_SVC_TOKEN" "$TARGET_PATH"
    fi
done
